<template>
  <el-dialog title="修改头像" class="dialog-offset avater-dialog" :visible.sync="portraitOpen" width="380px" :modal-append-to-body="false" :close-on-click-modal="false">
      <el-row>
        <el-col :style="{height: '250px'}">
          <vue-cropper
            ref="cropper"
            :img="cascaderOptions.img"
            :info="true"
            :output-type="cascaderOptions.outputType"
            :auto-crop="cascaderOptions.autoCrop"
            :auto-crop-width="cascaderOptions.autoCropWidth"
            :auto-crop-height="cascaderOptions.autoCropHeight"
            :fixed-box="cascaderOptions.fixedBox"
          />
        </el-col>
      </el-row>
      <div class="avatar-btn">
          <el-upload action="#" accept="image/*" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small">
              选择图片
            </el-button>
          </el-upload>
          <el-button icon="el-icon-plus" size="mini" @click="changeScale(1)" />
          <el-button icon="el-icon-minus" size="mini" @click="changeScale(-1)" />
          <el-button icon="el-icon-refresh-left" size="mini" @click="rotateLeft()" />
          <el-button icon="el-icon-refresh-right" size="mini" @click="rotateRight()" />
          <el-button type="primary" style="width: 64px;" size="mini" :loading="loading" @click="uploadImg()">保存</el-button>
      </div>
  </el-dialog>
</template>
<script>
import { VueCropper } from 'vue-cropper'
import { updateUser, uploadImg } from '@/api/user'
export default {
  name: 'AvaterDialog',
  components: { VueCropper },
  props: {
    visible: Boolean,
    avatar: String
  },
  data () {
    return {
      loading: false,
      cascaderOptions: {
        img: '', // 裁剪图片的地址
        outputType: 'png',
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true // 固定截图框大小 不允许改变
      }
    }
  },
  computed: {
    portraitOpen: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.cascaderOptions.img = this.avatar
      }
    }
  },
  methods: {
    // 覆盖默认的上传行为
    requestUpload () {
    },
    // 向左旋转
    rotateLeft () {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight () {
      this.$refs.cropper.rotateRight()
    },
    // 图片缩放
    changeScale (num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 上传预处理
    beforeUpload (file) {
      if (file.type.indexOf('image/') === -1) {
        this.$PsMessage({ message: '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。', type: 'error' })
      } else if (file.size / 1024 / 1024 > 20) {
        this.$PsMessage({ message: '文件大小限制20M以内。', type: 'error' })
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.cascaderOptions.img = reader.result
        }
      }
    },
    // 上传图片
    uploadImg () {
      this.$refs.cropper.getCropBlob((img) => {
        if (this.loading) return
        if (img) {
          const forms = new FormData()
          const file = new File([img], `${new Date().getTime()}.png`)
          forms.append('file', file)
          this.loading = true
          this.$store.dispatch('user/checkStatus').then(() => {
            uploadImg(forms).then(res => {
              const url = res.data?.url
              const param = {
                Portrait: url
              }
              updateUser(param).then(() => {
                this.$store.dispatch('user/mergeUserInfo', { Portrait: url })
                this.portraitOpen = false
              }).finally(() => {
                this.loading = false
              })
            }).catch(() => {
              this.loading = false
            })
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.$PsMessage({
            message: '图片错误，请重新选择图片',
            type: 'error'
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-btn{
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  >.el-button{
    margin-left: 10px;
  }
}
.avater-dialog{
  /deep/.el-dialog__body{
    padding-top: 10px;
  }
}
</style>
